package com.jf.assistant;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;

import com.jf.assistant.databinding.ActivityMainBinding;
import com.jf.bean.AssistantTask;
import com.jf.controller.MainController;
import com.jf.viewadapter.ActionTaskListAdapter;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private AccessibilityManager mAccessibilityManager;
    public ActivityMainBinding mainBinding;
    Rect clickbtrect;
    String jingdongpackagename="com.jingdong.app.mall";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());
        MyAccessibilityService.getInstance().init(this);

        mainBinding.startbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService();
            }
        });



        mainBinding.clickbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //clickbtrect = new Rect();
               // mainBinding.clickbutton.getGlobalVisibleRect(clickbtrect);
                //Toast.makeText(getApplicationContext(),"点击我了:"+clickbtrect.centerX()+clickbtrect.centerY(),Toast.LENGTH_SHORT).show();
               goApp(jingdongpackagename);
            }
        });



        mainBinding.addtask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });
        mainBinding.startfloatservice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (FloatingButtonService.isStarted) {
                    return;
                }
                if (!Settings.canDrawOverlays(MainActivity.this)) {
                    Toast.makeText(MainActivity.this, "当前无权限，请授权", Toast.LENGTH_SHORT);
                    startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
                } else {
                    startService(new Intent(MainActivity.this, FloatingButtonService.class));
                }
            }
        });
        try {
            initRview();
        }catch (Exception e){

        }


    }
    public void goApp(String packagename) {
        JfLog.logger( "goApp++++++++++++++++++++++++++++++++++++++++++++++++++++++：" + packagename);


        Intent intent = getPackageManager().getLaunchIntentForPackage(packagename);

        if (intent != null) {

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplication().startActivity(intent);
            JfLog.logger( "goApp++++++++++++++++++++++++++++++++++++++++++++++++++++++： 存在appintent" );
        }else {
            JfLog.logger( "goApp++++++++++++++++++++++++++++++++++++++++++++++++++++++： 不存在intent" );
        }


    }

     ArrayList<AssistantTask> mAssistantTasks;
    RecyclerView recyclerView;
     ActionTaskListAdapter actionTaskListAdapter;


    @Override
    protected void onResume() {
        super.onResume();
        try {
            //ArrayList<AssistantTask> mAssistantTasks1=MainController.getAssistantTask(this);
            JfLog.logger("onResume");
            initRview();

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("WrongConstant")
    public void initRview() throws ParseException {


         mAssistantTasks= MainController.getAssistantTask(this);

        if (mAssistantTasks!=null){

        }else {
            mAssistantTasks=new ArrayList<AssistantTask>();
        }

        recyclerView = mainBinding.rlview;
        LinearLayoutManager layoutManager = new LinearLayoutManager(this );
//设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
//设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper. VERTICAL);
         actionTaskListAdapter = new ActionTaskListAdapter(mAssistantTasks, this);
//        new NormalAdapter
//设置Adapter
        recyclerView.setAdapter(actionTaskListAdapter);
        //设置分隔线
       // recyclerView.addItemDecoration( new DividerGridItemDecoration(this ));
        //设置增加或删除条目的动画
       // recyclerView.setItemAnimator( new DefaultItemAnimator());
    }
    private void startService() {

     boolean is=   MyAccessibilityService.getInstance().checkAccessibilityEnabled("珈凡服务");
        if (is){
            Toast.makeText(this,"运行服务中",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this,"没有运行服务",Toast.LENGTH_SHORT).show();
            MyAccessibilityService.getInstance().goAccess();
        }
    }


    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (actionTaskListAdapter!=null){
            actionTaskListAdapter.notifyDataSetChanged();
        }

    }

    /**
     * Check当前辅助服务是否启用
     *
     * @param serviceName serviceName
     * @return 是否启用
     */
    private boolean checkAccessibilityEnabled(String serviceName) {
        List<AccessibilityServiceInfo> accessibilityServices =
                mAccessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        for (AccessibilityServiceInfo info : accessibilityServices) {
            if (info.getId().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 前往开启辅助服务界面
     */
    public void goAccess() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                startService(new Intent(MainActivity.this, FloatingButtonService.class));
            }
        }
    }
}
